﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GDI_应用案例.Pages.Controls
{
    public class ClockControl : Control
    {
        private System.Timers.Timer _timer;
        public ClockControl()
        {
            _timer=new System.Timers.Timer();
            _timer.Elapsed += _timer_Elapsed;
            _timer.Interval = 1000;
            _timer.Start();
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Clock(e.Graphics);
        }

        private void Clock(Graphics g)
        {
            const double pi = Math.PI; //声明数学公式中的pi 
            Point center = new Point(this.Width>>1, this.Height>>1); //创建 Point 实例 
            DateTime time = DateTime.Now; //获取当前时间 
                                          //读取时间
            double sec = 2.0 * pi * time.Second / 60.0;
            double min = 2.0 * pi * (time.Minute + time.Second / 60.0) / 60.0; 
            double hour = 2.0 * pi * (time.Hour + time.Minute / 60.0) / 12.0;//各指针单位换算
            int r = Math.Min(this.Width, this.Height) / 2; 
            int secHandLength = (int)(0.55 * r); 
            int minHandLength = (int)(0.55 * r); 
            int hourHandLength = (int)(0.45 * r);//刷新指针

            Pen SPen = new Pen(this.ForeColor, 1);
            g.DrawLine(SPen, center, new Point((int)(secHandLength * Math.Sin(sec)),(int)(-secHandLength * Math.Cos(sec)))); //绘制秒针 
            Pen MPen = new Pen(ForeColor, 2);
            g.DrawLine(MPen, center, new Point((int)(minHandLength * Math.Sin(min)), (int)(-minHandLength * Math.Cos(min)))); //绘制分针 
            Pen HPen = new Pen(ForeColor, 2);
            g.DrawLine(HPen, center, new Point((int)(hourHandLength * Math.Sin(hour)),(int)(-hourHandLength * Math.Cos(hour)))); //绘制时针

            HPen.Dispose();
            MPen.Dispose();
            SPen.Dispose();
        }
    }
}